<?php

use sef\controller;
use sef\model;
use weixin\mp;

class mp_controller extends  controller {

    public function receive() {
        import('weixin/mp/helper');
        import('weixin/mp/msg_receiver');
        import('socket_client');
        $msg_receiver = new mp\msg_receiver();
        $data = $msg_receiver -> request();

        //调试
        //$this -> add_log(var_export($data, 1));

        //判断是否有其他正在进行中的会话
        $where[] = array('is_finish', 'eq', 0);
        $where[] = array('from_user_name', 'eq', $data['FromUserName']);
        $talk = model('kf_talk') -> where($where) -> select('id,user_id,user_name,is_accept,type') -> find();

        if ($talk !== false) {
            //有进行中的会话
            $data['talk_id'] = $talk['id'];

            if ($talk['is_accept'] == 1) {
                $msg['to'] = array($talk['user_id']);
                $msg['type'] = 'transfer';
                $msg['data']['type'] = 'new_msg';
                $msg['data']['talk_id'] = $talk['id'];
                $msg['data']['create_time'] = $data['CreateTime'];
            } else {
                $msg['type'] = 'broadcast';
                $msg['data']['type'] = 'new_todo';
                $msg['data']['talk_id'] = $talk['id'];
                $msg['data']['create_time'] = $data['CreateTime'];
                $msg['data']['from_user_name'] = $data['FromUserName'];
            }

            $socket_client = new socket_client();
            @$socket_client -> send($msg);

        } else {
            //新的会话
            $talk_data['from_user_name'] = $data['FromUserName'];
            $talk_id = model('kf_talk') -> add($talk_data);
            $data['talk_id'] = $talk_id;

            $msg['type'] = 'broadcast';
            $msg['data']['type'] = 'new_todo';
            $msg['data']['talk_id'] = $talk_id;
            $msg['data']['create_time'] = $data['CreateTime'];
            $msg['data']['from_user_name'] = $data['FromUserName'];

            $socket_client = new socket_client();
            @$socket_client -> send($msg);

        }

        //事件类型
        $msg_type = $data['MsgType'];
        if ($msg_type == 'event') {
            //扫码提醒
            if ($data['Event'] == 'SCAN') {
                $type = substr($data['EventKey'], 4);

                $where_online[] = array('type', 'eq', $type);
                $where_online[] = array('openid', 'eq', $data['FromUserName']);

                $count_online = model('kf_online') -> where($where_online) -> count();

                if ($count_online > 0) {
                    model('kf_online') -> where($where_online) -> delete();
                    $content = '取消微信提醒';
                } else {
                    $online['openid'] = $data['FromUserName'];
                    $online['type'] = $type;
                    model('kf_online') -> add($online);
                    $content = '开启微信提醒';
                }
                import('weixin/mp/msg_sender');

                $msg_sender = new mp\msg_sender();

                //发送文字
                $msg['touser'] = $data['FromUserName'];
                $msg['msgtype'] = 'text';
                $msg['text']['content'] = $content;
                $msg_sender -> send($msg);
            }

            //关注
            if ($data['Event'] == 'subscribe') {
                $where_reply[] = array('name', 'eq', '关注');
                $reply = model('kf_reply') -> where($where_reply) -> get_field('content');

                $this -> reply($data['talk_id'], $data['FromUserName'], $reply);
                die('success');
            }
            //取消关注
            if ($data['Event'] == 'unsubscribe') {
                die('success');
            }
            //点击菜单
            if ($data['Event'] == 'CLICK') {
                //报案
                if ($data['EventKey'] == 'BAOAN') {
                    if ($talk !== false && $talk['type'] !== 1) {

                        //自动回复
                        $reply = '因发起报案，之前会话自动结束';
                        $this -> reply($data['talk_id'], $data['FromUserName'], $reply);

                        //结束会话
                        $data_finish['is_finish'] = 1;
                        $data_finish['is_accept'] = 1;
                        $data_finish['id'] = $talk['id'];
                        model('kf_talk') -> save($data_finish);

                        //新的会话
                        $talk_data['from_user_name'] = $data['FromUserName'];                        
                        $talk_id = model('kf_talk') -> add($talk_data);
                        $data['talk_id'] = $talk_id;

                        $msg['type'] = 'broadcast';
                        $msg['data']['type'] = 'new_todo';
                        $msg['data']['talk_id'] = $talk_id;
                        $msg['data']['create_time'] = $data['CreateTime'];
                        $msg['data']['from_user_name'] = $data['FromUserName'];

                        $socket_client = new socket_client();
                        @$socket_client -> send($msg);

                    }

                    $type['type'] = 1;
                    $type['id'] = $data['talk_id'];
                    model('kf_talk') -> save($type);

                    $data['MsgType'] = 'text';
                    $data['Content'] = '报案';

                    $this -> add_talk_log($data);

                    $where_reply[] = array('name', 'eq', '报案');
                    $reply = model('kf_reply') -> where($where_reply) -> get_field('content');
                    $this -> reply($data['talk_id'], $data['FromUserName'], $reply);

                    //微信提醒
                    import('weixin/mp/msg_sender');
                    $msg_sender = new mp\msg_sender();

                    //微信通知
                    $where_online[] = array('type', 'eq', 1);
                    $kf_list = model('kf_online') -> where($where_online) -> get_list();
                    foreach ($kf_list as $kf) {
                        $msg['touser'] = $kf['openid'];
                        $msg['msgtype'] = 'text';
                        $msg['text']['content'] = '有新的报案，请及时处理';
                        $msg_sender -> send($msg);
                    }
                    die('success');
                }

                //举报
                if ($data['EventKey'] == 'XIANSUO') {
                    if ($talk !== false && $talk['type'] !== 2) {

                        //自动回复
                        $reply = '因发起举报，之前会话自动结束';
                        $this -> reply($data['talk_id'], $data['FromUserName'], $reply);

                        //结束会话
                        $data_finish['is_finish'] = 1;
                        $data_finish['is_accept'] = 1;
                        $data_finish['id'] = $talk['id'];
                        model('kf_talk') -> save($data_finish);

                        //新的会话
                        $talk_data['from_user_name'] = $data['FromUserName'];                        
                        $talk_id = model('kf_talk') -> add($talk_data);
                        $data['talk_id'] = $talk_id;

                        $msg['type'] = 'broadcast';
                        $msg['data']['type'] = 'new_todo';
                        $msg['data']['talk_id'] = $talk_id;
                        $msg['data']['create_time'] = $data['CreateTime'];
                        $msg['data']['from_user_name'] = $data['FromUserName'];

                        $socket_client = new socket_client();
                        @$socket_client -> send($msg);

                    }

                    $type['type'] = 2;
                    $type['id'] = $data['talk_id'];
                    model('kf_talk') -> save($type);

                    $data['MsgType'] = 'text';
                    $data['Content'] = '举报';
                    $this -> add_talk_log($data);

                    $where_reply[] = array('name', 'eq', '举报');
                    $reply = model('kf_reply') -> where($where_reply) -> get_field('content');
                    $this -> reply($data['talk_id'], $data['FromUserName'], $reply);

                    //微信提醒
                    import('weixin/mp/msg_sender');
                    $msg_sender = new mp\msg_sender();

                    $where_online[] = array('type', 'eq', 2);
                    $kf_list = model('kf_online') -> where($where_online) -> get_list();
                    foreach ($kf_list as $kf) {
                        $msg['touser'] = $kf['openid'];
                        $msg['msgtype'] = 'text';
                        $msg['text']['content'] = '有新的举报，请及时处理';
                        $msg_sender -> send($msg);
                    }
                    die('success');
                }
            }
        } else {
            $this -> add_talk_log($data);
        }
        //文本消息
        if ($msg_type == 'text') {
            //自动回复
            $keyword = trim($data['Content']);
            $where_reply[] = array('keyword', 'eq', $keyword);
            $reply = model('kf_reply') -> where($where_reply) -> get_field('content');

            if (!empty($reply)) {
                $msg['text']['content'] = $reply;
                $msg['touser'] = $data['FromUserName'];
                $msg['msgtype'] = 'text';
                $this -> reply($data['talk_id'], $data['FromUserName'], $reply);
            }
        }

        //图片和音频
        if ($msg_type == 'image' or $msg_type == 'voice') {
            $media_id = $data['MediaId'];
            $msg_receiver -> download_media($msg_type, $media_id, null);
        }

        //视频
        if ($msg_type == 'video') {
            $media_id = $data['MediaId'];
            $thumb_media_id = $data['ThumbMediaId'];
            $msg_receiver -> download_media($msg_type, $media_id, $thumb_media_id);
        }

        //添加人员信息
        $user_info = $msg_receiver -> get_user_info($data['FromUserName']);
        $this -> add_vistor($user_info);

        die('success');
    }

    private function add_talk_log($data) {
        $new['action_type'] = 'receive';

        if (isset($data['ToUserName'])) {
            $new['to_user_name'] = $data['ToUserName'];
        }
        if (isset($data['FromUserName'])) {
            $new['from_user_name'] = $data['FromUserName'];
        }
        if (isset($data['CreateTime'])) {
            $new['create_time'] = $data['CreateTime'];
        }
        if (isset($data['MsgType'])) {
            $new['msg_type'] = $data['MsgType'];
        }
        if (isset($data['Content'])) {
            $new['content'] = $data['Content'];
        }
        if (isset($data['MsgId'])) {
            $new['msg_id'] = $data['MsgId'];
        }
        if (isset($data['PicUrl'])) {
            $new['pic_url'] = $data['PicUrl'];
        }
        if (isset($data['MediaId'])) {
            $new['media_id'] = $data['MediaId'];
        }
        if (isset($data['Format'])) {
            $new['format'] = $data['Format'];
        }
        if (isset($data['Recognition'])) {
            $new['recognition'] = $data['Recognition'];
        }
        if (isset($data['ThumbMediaId'])) {
            $new['thumb_media_id'] = $data['ThumbMediaId'];
        }
        if (isset($data['Location_X'])) {
            $location['x'] = $data['Location_X'];
        }
        if (isset($data['Location_Y'])) {
            $location['y'] = $data['Location_Y'];
        }
        if (isset($data['Scale'])) {
            $location['scale'] = $data['Scale'];
        }
        if (isset($location)) {
            $new['location'] = json_encode($location);
        }
        if (isset($data['Label'])) {
            $new['label'] = $data['Label'];
        }

        $new['talk_id'] = $data['talk_id'];

        model('kf_talk_log') -> add($new);
    }

    public function reply($talk_id, $open_id, $content) {

        $data['talk_id'] = $talk_id;
        $data['msg_type'] = 'text';
        $data['to_user_name'] = $open_id;
        $data['content'] = $content;
        $data['action_type'] = 'send';
        $data['create_time'] = time();
        $data['user_id'] = 0;
        $data['user_name'] = '自动回复';

        $id = model('kf_talk_log') -> add($data);

        import('weixin/mp/helper');
        import('weixin/mp/msg_sender');

        $msg_sender = new mp\msg_sender();

        //发送文字
        $msg['touser'] = $open_id;
        $msg['msgtype'] = 'text';
        $msg['text']['content'] = $content;
        $msg_sender -> send($msg);
    }

    private function add_vistor($user_info) {

        $model = model('kf_vistor');
        $where[] = array('openid', 'eq', $user_info["openid"]);
        $ret = $model -> where($where) -> find();
        if ($ret == false) {
            $data['subscribe'] = $user_info['subscribe'];
            $data['openid'] = $user_info['openid'];
            $data['nickname'] = $user_info['nickname'];
            $data['sex'] = $user_info['sex'];
            $data['city'] = $user_info['city'];
            $data['country'] = $user_info['country'];
            $data['province'] = $user_info['province'];
            $data['language'] = $user_info['language'];
            $data['headimgurl'] = $user_info['headimgurl'];
            $data['subscribe_time'] = $user_info['subscribe_time'];
            $model -> add($data);
            $head_image = file_get_contents($user_info['headimgurl']);
            file_put_contents('uploads/mp/avatar/' . $user_info['openid'] . '.jpg', $head_image);
        }
    }

    public function add_log($data) {
        file_put_contents('error_log.txt', $data, FILE_APPEND);
    }

}
